<template>
  <div :width="480" :mask-closable="false" :cancel="handleClose" hide-cancel>
    <div v-if="data.length > 0" class="get-ip-table">
      <div v-for="(i, index) in data" :key="index" class="get-ip-table-row">
        <div class="get-table-ip">{{ i.ip }}</div>
        <div class="get-table-type">
          <a-link v-if="i.used" :hoverable="false" :disabled="i.used">
            已使用
          </a-link>
          <a-link
            v-else
            :hoverable="false"
            :disabled="useDisabled"
            @click="useIp(i.ip)">
            使用
          </a-link>
        </div>
      </div>
    </div>
    <div v-else class="get-ip-empty">暂无数据</div>
  </div>
</template>
<script lang="ts" setup>
interface IEmits {
  (e: 'validateIp'): void
}
const emits = defineEmits<IEmits>()
interface IProps {
  reportIps: Array<string>
}

const nodeIps = defineModel<Array<{ ip: string }>>('ips', { required: true })
const props = withDefaults(defineProps<IProps>(), {
  reportIps: () => []
})
const data = ref<Array<{ ip: string; used: boolean }>>([])
const useDisabled = computed(() => {
  const index = nodeIps.value.findIndex((item) => item.ip.length === 0)
  if (nodeIps.value.length > 9 && index === -1) {
    return true
  }
  return false
})
const useIp = (ip: string) => {
  const index = nodeIps.value.findIndex((item) => item.ip.length === 0) // 查找ip列表是否有空行
  if (index !== -1) {
    // 有空行则向其中添加数据
    nodeIps.value[index] = { ip }
  } else {
    // 没有则添加新行
    nodeIps.value.push({ ip })
  }
  emits('validateIp')
}

const handleClose = () => {}
watch(
  () => nodeIps.value,
  (v) => {
    if (v) {
      data.value = props.reportIps?.map((ip) => {
        const index = nodeIps.value.findIndex((item) => item.ip === ip)
        const used = index !== -1 ? true : false

        return { ip, used }
      })
    }
  },
  { immediate: true, deep: true }
)
</script>

<style lang="less" scoped>
.get-ip-table {
  max-height: 422px;
  overflow: auto;
  padding-right: 14px;
  .get-ip-table-row {
    display: flex;
    width: 200px;
    align-items: flex-start;

    .get-table-ip {
      display: flex;
      padding: 8px 0px;
      align-items: center;
      gap: 6px;
      flex: 1 0 0;
      color: var(---color-text-2, #393c40);
      font-size: 14px;
      line-height: 22px; /* 157.143% */
    }
    .get-table-type {
      display: flex;
      padding: 8px 0px;
      justify-content: flex-end;
      align-items: center;
      gap: 6px;
      flex-shrink: 0;
      font-size: 14px;
      line-height: 22px; /* 157.143% */
    }
  }
}
.get-ip-empty {
  color: var(---color-text-6, #adafb2);
  font-size: 14px;
  line-height: 22px; /* 157.143% */
  padding: 0px 24px;
}
</style>
